import serial
import struct
import binascii
import multiprocessing
import sys
import logging
import time
import traceback
from multiprocessing import Process, Queue
import subprocess 
import os
import json
import asyncio
import http.client
import urllib
import socket
import time
import select
from time import ctime


CWD_DIR = os.path.split(os.path.abspath(__file__) )[0]

adress = "120.24.60.81"
port = 8800
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((adress,port))
epoll = select.epoll()  
#获取创建好的sock的文件描述符  
fd = sock.fileno()
epoll.register(fd,select.EPOLLIN)
class check(object):
	def __init__(self,checkTuple):
		self.power = checkTuple[0]
		self.name = checkTuple[1]
		self.state = checkTuple[2]
		self.id = 1234

def check_to_json(r):
	return{
	    'power':r.power,
		'name':r.name,
		'state':r.state,
		'id':r.id
	}

def list_to_json(listData):
	if not isinstance(listData, (list, tuple)):
		raise TypeError('bad operand type, parameter must be a tuple or list')
	list_json = []
	#for elem in listData:
	list_json.append(check(listData))
	dataJson = json.dumps(list_json,default=check_to_json,ensure_ascii=False)
	return dataJson

def httpSend(host, url, port, data_str):
	conn = http.client.HTTPConnection(host, port, timeout = 5)
	data = {'data':data_str}
	headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "*/*"}
	params = urllib.parse.urlencode(data)
	conn.request("POST", url, params, headers)

	response = conn.getresponse()
	data = response.read()
	conn.close()
	return data

def recv(serialPort):
	data_list = []	
	data_num = 0
	data_byte = serialPort.read(1)
	data_bytes = data_byte
	data_num += len(data_byte)

	while data_byte == b'\xaa' :		

		data_byte = serialPort.read(75) 
		data_num += len(data_byte)
		data_bytes += data_byte
		data_list = struct.  unpack('B'*data_num, data_bytes)
		return data_list
	


def receive0(q):
	t = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
	while not t.isOpen():
		t = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
	while True:
		try:
			data = recv(t)
			if data is not None and data[1]==187:
				cmd = ('./recognize '+ '%d '*68) %(data[6:-2])
				p = subprocess.Popen(cmd , shell=True , stdout=subprocess.PIPE , cwd=CWD_DIR)
				send =[] 
				name = p.stdout.read()
				name=name.decode('utf-8')
				print("检测到数据",name)
				for elem in name.split(','):
					send.append(elem)
				dataJson = list_to_json(send)
				print("数据正在上报阿里云",dataJson)
				q.put(dataJson)
				#bendi.data_write(dataJson)#仅此一处加入存入本地
				# try:
				# 	httpSend(OBJ_HOST, OBJ_URL, PORT, dataJson)
				# 	print("实时数据上报成功")
				# except :
				# 	print("实时数据上报失败")
				
	
		except Exception as e :
			print("error:",e)


def client(q):
	while True:
		events = epoll.poll(1)
		for fileno,event in events:
			if fileno == fd:
				if event & select.EPOLLIN:
					datas = sock.recv(128)
					if len(datas)>0:
						print("收到阿里云反向控制信息",datas.decode())
						zhiling = datas.decode()
					if len(datas) > 0:
						if (zhiling.split(';')[1]).split('=')[-1]=='1':
							if (zhiling.split(';')[-1]).split('=')[-1]=='off':
								print("正在关闭")
								t = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
								t1=bytes.fromhex('AA BB 00 EE FF')
								t1=t.write(t1)
							if (zhiling.split(';')[-1]).split('=')[-1]=='on':
								print("正在打开")
								t = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
								t1=bytes.fromhex('AA BB 01 EE FF')
								t1=t.write(t1)
						if (zhiling.split(';')[1]).split('=')[-1]=='2':
							if (zhiling.split(';')[-1]).split('=')[-1]=='off':
								print("正在关闭")
								t = serial.Serial('/dev/ttyUSB1', 115200, timeout=1)
								t1=bytes.fromhex('AA BB 00 EE FF')
								t1=t.write(t1)
							if (zhiling.split(';')[-1]).split('=')[-1]=='on':
								print("正在打开")
								t = serial.Serial('/dev/ttyUSB1', 115200, timeout=1)
								t1=bytes.fromhex('AA BB 01 EE FF')
								t1=t.write(t1)
						if (zhiling.split(';')[1]).split('=')[-1]=='3':
							if (zhiling.split(';')[-1]).split('=')[-1]=='off':
								print("正在关闭")
								t = serial.Serial('/dev/ttyUSB2', 115200, timeout=1)
								t1=bytes.fromhex('AA BB 00 EE FF')
								t1=t.write(t1)
							if (zhiling.split(';')[-1]).split('=')[-1]=='on':
								print("正在打开")
								t = serial.Serial('/dev/ttyUSB2', 115200, timeout=1)
								t1=bytes.fromhex('AA BB 01 EE FF')
								t1=t.write(t1)

def client1(q):
	while True:
		data=q.get()
		if len(data)>0:
			sock.send(('%s' % (data)).encode())
			print("数据已发送给了阿里云",data)
			
	
def main():
	while True:
		try:
			q = Queue()
			prev0 = Process(target=receive0, args=(q,))
			prev1 = Process(target=client, args=(q,))
			prev2 = Process(target=client1,args=(q,))
			prev0.start()
			prev1.start()
			prev2.start()
			break
		
		except:
			time.sleep(5)
			print("shumeipai正在重新连接服务器")
			continue

if __name__ == "__main__":
	main()


		



